package com.ruding.disruptor.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.LoggerFactory;


/**
 * Mapper代理
 * @author 520475
 *
 */
public class MapperProxy {
    
    @SuppressWarnings("unchecked")
    public static <T> T getMapper(Class<T> clazz) {
        
        Object proxy = Proxy.newProxyInstance(MapperProxy.class.getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() {
            
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object obj = null;
                try {
                    SqlSession sqlSession = SqlSessionFactoryUtil.openSession();
                    T t = sqlSession.getMapper(clazz);
                    obj = method.invoke(t, args);
                    //每次mapper操作完成提交、关闭
                    if(sqlSession != null) {
                        sqlSession.commit();
                        sqlSession.close();
                    }
                }catch (Exception e) {
                    LoggerFactory.getLogger(clazz).error(e.getMessage(), e);
                    throw e;
                }
                
                return obj;
            }
        });
        return (T) proxy;
    }

}
